package com.Xht.www.servlet;

//后端响应查询房型信息的请求

import com.Xht.www.dao.MerchantInfoDAO;
import com.Xht.www.dao.RoomTypeInfoDAO;
import com.Xht.www.dao.UserBrowsingHistoryDAO;
import com.Xht.www.po.RoomTypeInfoPO;
import com.Xht.www.po.UserBrowsingHistoryPO;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;

@WebServlet("/room-type-info")
public class RoomTypeInfoServlet extends HttpServlet {
    private MerchantInfoDAO merchantDAO = new MerchantInfoDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        String merchantName = request.getParameter("merchantName");
        String merchantIdParam = request.getParameter("merchantId");
        String userIdParam = request.getParameter("userId");


        if (merchantName != null && !merchantName.isEmpty()) {
            // 获取商家ID
            Integer merchantId = merchantDAO.getMerchantIdByName(merchantName);
            if (merchantId == null) {
                System.out.println("未找到商家ID，名称: " + merchantName);
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().write("{\"error\":\"未找到指定商家\"}");
                return;
            }
            System.out.println("收到的请求参数:");
            System.out.println("merchantName: " + merchantName);
            System.out.println("merchantId: " + merchantIdParam);
            System.out.println("userId: " + userIdParam);

            // 记录浏览历史
            if (merchantName != null && !merchantName.isEmpty()) {
                if (merchantIdParam != null && !merchantIdParam.equals("undefined") &&
                        userIdParam != null && !userIdParam.equals("undefined")) {

                    try {
                        Integer userId = Integer.parseInt(userIdParam);

                        UserBrowsingHistoryPO history = new UserBrowsingHistoryPO();
                        history.setUserId(userId);
                        history.setMerchantId(merchantId);
                        history.setMerchantName(merchantName);
                        history.setBrowsingTime(new Timestamp(System.currentTimeMillis()));

                        UserBrowsingHistoryDAO historyDAO = new UserBrowsingHistoryDAO();

                        boolean inserted = historyDAO.insertBrowsingHistory(history);


                    } catch (NumberFormatException e) {
                        System.err.println("无法解析 merchantId 或 userId：" + e.getMessage());
                    } catch (SQLException e) {
                        System.err.println("数据库操作失败：" + e.getMessage());
                        e.printStackTrace();
                    }
                }
            }

            // 查询房型信息并返回 JSON
            RoomTypeInfoDAO roomTypeInfoDAO = new RoomTypeInfoDAO();
            try {
                List<RoomTypeInfoPO> roomTypeInfoList = roomTypeInfoDAO.queryRoomTypeInfoByMerchantName(merchantName);
                StringBuilder json = new StringBuilder("[");
                for (int i = 0; i < roomTypeInfoList.size(); i++) {
                    RoomTypeInfoPO roomTypeInfo = roomTypeInfoList.get(i);
                    json.append("{")
                            .append("\"roomTypeId\":").append(roomTypeInfo.getRoomTypeId()).append(",")
                            .append("\"merchantName\":\"").append(roomTypeInfo.getMerchantName()).append("\",")
                            .append("\"bedType\":\"").append(roomTypeInfo.getBedType()).append("\",")
                            .append("\"remainingQuantity\":").append(roomTypeInfo.getRemainingQuantity()).append(",")
                            .append("\"keywords\":\"").append(roomTypeInfo.getKeywords()).append("\",")
                            .append("\"price\":\"").append(roomTypeInfo.getPrice()).append("\",")
                            .append("\"salesVolume\":").append(roomTypeInfo.getSalesVolume())
                            .append("}");
                    if (i < roomTypeInfoList.size() - 1) {
                        json.append(",");
                    }
                }
                json.append("]");
                response.getWriter().write(json.toString());

            } catch (SQLException e) {
                e.printStackTrace();
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("{\"error\":\"数据库查询失败\"}");
            }
        }
    }
}
